import React, { useEffect, useState } from 'react'
import { Button, Image, message, Modal, Space, Spin, Table } from 'antd'
import http from '@/utils/request'
import Filter from '@/components/filter'
import './index.scss'
import { authority } from '@/assets/dict/authCode'

interface filterType {
  pageSize?: number,
  pageNum?: number,
  current?: number,
  customerName?: string,
  customerPhone?: string
}

interface FileItem {
  id: string;
  customerName: string;
  customerPhone: string;
  fileType: string;
  fileUrl: string;
  aliyunUrl: string;
  createTime: string;
  [key: string]: any;
}

const OssFile: React.FC = () => {
  const [dataSource, setDataSource] = useState<FileItem[]>([])
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(false)
  const [previewVisible, setPreviewVisible] = useState(false)
  const [previewUrl, setPreviewUrl] = useState('')
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])
  const [pageConfig, setPageConfig] = useState<filterType>({
    pageSize: 10,
    pageNum: 1,
    current: 1,
    customerName: '',
    customerPhone: ''
  })

  const queryFileList = () => {
    setLoading(true)
    http.post('/disp/biz/aliyun/page', {
      ...Object.fromEntries(Object.entries(pageConfig).filter(([_, val]) => val && _ !== 'current'))
    }).then(res => {
      setTotal(res.data.total || 0)
      setDataSource(res.data.list || [])
    }).finally(() => {
      setLoading(false)
    })
  }

  useEffect(() => {
    queryFileList()
  }, [])

  const pageChange = (pageNum: number, pageSize: number) => {
    pageConfig.pageSize = pageSize
    pageConfig.pageNum = pageNum
    pageConfig.current = pageNum
    queryFileList()
  }

  const filterChange = (val: any, key: string) => {
    setPageConfig((config) => ({
      ...config,
      pageNum: 1,
      current: 1,
      [key]: val
    }))
  }

  const previewFile = (record: FileItem) => {
    const fileType = record.fileType?.toLowerCase() || ''
    const isVideo = fileType.includes('video') || fileType.includes('mp4') || fileType.includes('avi') || fileType.includes('mov')
    
    if (isVideo) {
      setPreviewUrl(record.aliyunUrl)
      setPreviewVisible(true)
    } else {
      const image = document.createElement('div')
      image.innerHTML = `
        <div style="display: none;">
          <img src="${record.aliyunUrl}" />
        </div>
      `
      document.body.appendChild(image)
      const img = image.querySelector('img')
      if (img) {
        const event = new MouseEvent('click', {
          view: window,
          bubbles: true,
          cancelable: true
        })
        img.dispatchEvent(event)
        
        setTimeout(() => {
          document.body.removeChild(image)
        }, 100)
      }
    }
  }

  const handlePreviewCancel = () => {
    setPreviewVisible(false)
    setPreviewUrl('')
  }

  const batchDownload = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要下载的文件')
      return
    }
    setLoading(true)
    http.post('/disp/biz/aliyun/batchDownloadForAliyunUrl', selectedRowKeys).then(res => {
      console.log(res.data)
      if (res.data) {
        window.open(res.data, '_blank')
      } else {
        message.error('获取下载链接失败')
      }
    }).catch(err => {
      console.error('批量下载失败:', err)
      message.error('批量下载失败')
    }).finally(() => {
      setLoading(false)
    })
  }

  const handleDownload = (record: FileItem) => {
    window.open(record.aliyunUrl, '_blank')
    http.get('/disp/biz/aliyun/updateDownloadFlag', {
      params: {
        id: record.id
      }
    })
  }

  const handleDelete = (record: FileItem) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除该文件吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          setLoading(true)
          await http.get('/disp/biz/aliyun/deleteAliyunFile', {
            params: {
              id: record.id
            }
          })
          message.success('删除成功')
          queryFileList()
        } catch (error) {
          console.error('删除失败:', error)
          message.error('删除失败')
        } finally {
          setLoading(false)
        }
      }
    })
  }

  const rowSelection = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setSelectedRowKeys(newSelectedRowKeys)
    }
  }

  const columns = [
    {
      title: '客户姓名',
      dataIndex: 'customerName',
      key: 'customerName'
    },
    {
      title: '客户手机',
      dataIndex: 'customerPhone',
      key: 'customerPhone'
    },
    {
      title: '上传人',
      dataIndex: 'updateUserName',
      key: 'id'
    },
    {
      title: '地址',
      dataIndex: 'fullAddressName',
      key: 'id'
    },
    {
      title: '文件名',
      dataIndex: 'fileName',
      key: 'id'
    },
    {
      title: '文件大小',
      dataIndex: 'fileSize',
      key: 'id'
    },
    {
      title: '文件类型',
      dataIndex: 'fileType',
      key: 'fileType'
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime'
    },
    {
      title: '预览',
      key: 'preview',
      render: (_: any, record: FileItem) => {
        const fileType = record.fileType?.toLowerCase() || ''
        const isVideo = fileType.includes('video') || fileType.includes('mp4') || fileType.includes('avi') || fileType.includes('mov')
        if (isVideo) {
          return <a onClick={() => previewFile(record)}>预览</a>
        } else {
          return (
            <Image
              src={record.aliyunUrl}
              width={40}
              height={40}
              style={{ objectFit: 'cover', cursor: 'pointer' }}
              preview={{ src: record.aliyunUrl }}
              fallback="https://via.placeholder.com/40x40?text=无图"
            />
          )
        }
      }
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      fixed: 'right',
      render: (_: any, record: FileItem) => (
        <Space size="middle">
          {authority('ossfile-delete', <a onClick={() => handleDelete(record)}>删除</a>)}
          {authority('ossfile-download', <a onClick={() => handleDownload(record)}>下载</a>)}
        </Space>
      )
    }
  ]

  const filterOptions = [
    {
      label: '客户姓名',
      key: 'customerName',
      type: 'input',
      placeholder: '请输入客户姓名'
    },
    {
      label: '客户手机',
      key: 'customerPhone',
      type: 'input',
      placeholder: '请输入客户手机'
    }
  ]

  return (
    <Spin spinning={loading}>
      <Filter
        items={filterOptions}
        onChange={filterChange}
        onSure={queryFileList}
        otherBtn={
          authority('ossfile-download-batch', <Button
            style={{ marginLeft: '20px' }}
            onClick={batchDownload}
            disabled={selectedRowKeys.length === 0}
          >
            批量下载
          </Button>)
        }
      />
      <Table
        rowSelection={rowSelection}
        pagination={{ 
          position: ['bottomRight'], 
          ...pageConfig, 
          total, 
          onChange: pageChange,
          showTotal: (total) => `共 ${total} 条`,
          pageSizeOptions: ['10', '20', '30', '50'],
          showSizeChanger: true
        }}
        scroll={{ x: 1500 }}
        dataSource={dataSource}
        columns={columns}
        rowKey="id"
      />
      <Modal
        title="视频预览"
        open={previewVisible}
        footer={null}
        onCancel={handlePreviewCancel}
        width="50vw"
        centered
        styles={
          {
            body:{
              maxHeight: 'calc(100vh - 200px)',
              overflow: 'hidden',
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center'
            }
          }
        }
      >
        <video
          controls
          style={{ 
            maxWidth: '100%',
            maxHeight: 'calc(100vh - 200px)',
            objectFit: 'contain'
          }}
          src={previewUrl}
        >
          您的浏览器不支持视频播放
        </video>
      </Modal>
    </Spin>
  )
}

export default OssFile
